/**
 * 并发控制
 */

 class Request{
    constructor({limt=4}){
        this.limt = limt
        this.resolveArr = [] // 收集resolve
        this.currIndex = 0
    }

    async request(fun){
        if(typeof fun !== 'function') {
            throw new Error('is not Function')
        };
        if(this.currIndex >= this.limt){
            await new Promise((resolve)=>{this.resolveArr.push(resolve)}) 
        }
        return this.handle(fun)
    }

    async handle(fun){
        this.currIndex++
        try{
            return await fun()
        }catch(e){
            return Promise.reject(e)
        }finally{
            this.currIndex--
            if(this.resolveArr.length){
                this.resolveArr[0]()
                this.resolveArr.shift()
            }
        }
    }
}
const request = new Request({limt:4})
// 一个并发控制
export function createRequest(){
    return request.request.bind(request)
}